package com.example.ttl1.service;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * ClassName:MessageService
 * Package:com.example.ttl1.service
 * Description:
 *
 * @Author:ZhangXin
 * @Create:2023/8/11-21:30
 * @Version:v1.0
 */
@Service
@Slf4j
public class MessageService {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${my.exchangeName}")
    private String exchangeName;

    /**
     * 设置发布者的确认模式
     * 构造方法执行后自动执行
     */
    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(
                //开启生产者的确认模式
                (CorrelationData, ack, cause) -> {
                    if (!ack) {
                        log.error("消息没有到达交换机,原因为：{}", cause);
                        //TODO 重发消息或者记录错误日志
                    }
                }
        );
        rabbitTemplate.setReturnsCallback(
                new RabbitTemplate.ReturnsCallback() {
                    @Override
                    public void returnedMessage(ReturnedMessage returned) {
                        log.error("消息没有从交换机正确的投递(路由)到队列,原因为：{}",returned.getReplyText());
                    }
                }
        );
    }

    public void sendMsg() {
        MessageProperties messageProperties = new MessageProperties();
        //设置单条消息的持久化
        messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);

        Message message = MessageBuilder.withBody("过期时间TTL".getBytes()).andProperties(messageProperties).build();

        rabbitTemplate.convertAndSend(exchangeName, "info", message);

        log.info("消息发送完毕,发送时间为:{}", new Date());
    }
}
